<template>
  <VTable ref="tableRef" v-bind="tableOptions">
    <template #form="{ form }">
      <VSelect v-model="form.shop_ids" placeholder="店铺名称" :options="options.shop" multiple collapse-tags showCheckAll paste style="min-width: 240px" />
      <VSelect v-model="form.shop_statuses" placeholder="店铺状态" :options="options.shop_status" multiple collapse-tags showCheckAll style="min-width: 160px" />
      <!-- <VSelect v-model="form.auth_status" placeholder="授权状态" :options="options.auth_status" multiple collapse-tags style="min-width: 160px" /> -->
      <VCascader v-model="form.preferred_saleman_id" placeholder="首选业务员" multiple collapse-tags style="min-width: 160px" />
      <VCascader v-model="form.salesman_id" placeholder="业务员" multiple collapse-tags style="min-width: 160px" />
      <VCascader v-model="form.preferred_customer_service_id" placeholder="首选客服人员" multiple collapse-tags style="min-width: 160px" />
      <VCascader v-model="form.customer_service_id" placeholder="客服人员" multiple collapse-tags style="min-width: 160px" />
      <VSelect v-model="form.is_download_orders" placeholder="是否下载订单/报表" :options="options.open" multiple collapse-tags style="min-width: 180px" />
      <VSelect v-model="form.is_pre_generate" placeholder="是否预生成追踪号" :options="options.open" multiple collapse-tags style="min-width: 170px" />
      <VSelect v-model="form.is_platform_shipment" placeholder="是否标记平台发货" :options="options.open" multiple collapse-tags style="min-width: 170px" />
    </template>
    <template #toolbar_btns>
      <VButton :auth="`${authPath}/create`" type="primary" icon="DocumentAdd" @click="create(tableRef)">添加店铺</VButton>
      <VButton :auth="`${authPath}/edit-salesman`" @click="handleBatch('aditSalesman')">修改业务员</VButton>
      <VButton :auth="`${authPath}/edit-brand`" @click="handleBatch('brand')">默认品牌</VButton>
      <EditOrder :tableRef="tableRef" :options="options" @success="query" />
      <VExport :auth="`${authPath}/export`" mainKey="shop_id" name="shop_other" :tableRef="tableRef" task class="ml-auto" />
    </template>
  </VTable>
  <Add ref="addRef" :options="options" :platform_id="platform_id" :platform_name="platform_name" @success="query">
    <template #default="{form, options}">
      <slot name="addAuth" v-bind="{form, options}" />
    </template>
  </Add>
  <AditSalesman ref="aditSalesmanRef" :options="options" @success="query" />
  <Brand ref="brandRef" :options="options" @success="query" />
  <VLog ref="logRef" />
  <Register ref="registerRef" />
  <Credit ref="creditRef" />
  <Collect ref="collectRef" />
  <slot v-bind="{options}" />
</template>
  
<script setup lang="jsx">
import api from './api'
import Add from './Add'
import AditSalesman from '../../AditSalesman'
import Brand from '../../Brand'
import Register from '../../Register'
import Credit from '../../Credit'
import Collect from '../../Collect'
import EditOrder from '../../EditOrder'
import { getOption } from '@/api/public'
import { ElMessage, ElMessageBox } from 'element-plus'
const props = defineProps({
  type: { type: String, default: 'others' },
  platform_id: { type: Number, default: () => null },
  platform_name: { type: String, default: '' },
  tableOpts: { type: Object, default: () => ({}) },
})

const authPath = `/base/shop/others`

const baseName = `shop_${props.type}`
const tableRef = ref()
const logRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 新增
const addRef = ref()
const create = () => {
  if(props.type === 'others') {
    ElMessageBox.alert('请在具体的平台下添加店铺，如平台不存在，请联系 VitoMa(18823715767)', '提示', {
      // if you want to disable its autofocus
      // autofocus: false,
      confirmButtonText: '确定'
    })
  } else {
    addRef?.value.open()
  }
}

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: baseName }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

// 批量操作
const aditSalesmanRef = ref()
const brandRef = ref()
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const shop_ids = selection.map(d => d.shop_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    aditSalesman: () => {
      aditSalesmanRef?.value.open(shop_ids)
    },
    brand: () => {
      brandRef?.value.open(shop_ids)
    },
  }
  handle[name]()
}
// 单行操作
const registerRef = ref()
const creditRef = ref()
const collectRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { shop_id } = row
  const showLoading = (name = 'handle') => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = (name = 'handle') => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    edit: () => {
      addRef?.value.open(shop_id)
    },
    delete: () => {
      ElMessageBox.confirm('是否确认删除？', '取消', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.delete({ shop_ids: [shop_id] }).then(res => {
            ElMessage({ type: 'success', message: '操作成功', })
            query()
          }).finally(() => {
            closeLoading()
          })
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    status: () => {
      showLoading()
      api.status({ shop_ids: [shop_id], status: row.status === '启用' ? 2 : 1 }).then(res => {
        ElMessage({ type: 'success', message: '操作成功', })
        query()
      }).finally(() => {
        closeLoading()
      })
    },
    log: () => {
      logRef?.value.open({ type: baseName, record_id: shop_id})
    },
    register: () => {
      registerRef?.value.open(shop_id)
    },
    credit: () => {
      creditRef?.value.open(shop_id)
    },
    collect: () => {
      collectRef?.value.open(shop_id)
    },
  }
  handle[name]()
}

// 列表配置
const tableOptions = reactive({
  id: 'shop-otto',
  rowConfig: { height: 120 },
  scrollY: { enabled: true, oSize: 0 },
  // customConfig: { storage: true },
  // toolbarConfig: { custom: true },
  formConfig: {
    data: {
    }
  },
  columns: [
    { type: 'checkbox', fixed: 'left', width: 50 },
    {
      title: '店铺账号', minWidth: 180, slots: {
        default: ({ row }) => row.shop_name
      }
    },
    {
      title: '基本信息', minWidth: 200, slots: {
        default: ({ row }) => <div>
          <VText title='平台账号' value={row.basic_info.platform_account} />
          <VText title='店铺名' value={row.basic_info.amazon_shop_name} />
          <VText title='品牌' value={row.basic_info.brand} />
          <VText value={row.basic_info.shop_type} />
        </div>
      }
    },
    {
      title: '分配信息', minWidth: 200, slots: {
        default: ({ row }) => <div>
          <VText title='一级部门' value={row.alloc_info.first_level_department} />
          <VText title='二级部门' value={row.alloc_info.second_level_department} />
          <VText title='首选业务员' value={row.alloc_info.preferred_saleman_name} />
          <VText title='首要客服' value={row.alloc_info.preferred_customer_service_name} />
          <VText title='业务员' value={row.alloc_info.saleman_name} line='2' />
        </div>
      }
    },
    {
      title: '状态', minWidth: 160, slots: {
        default: ({ row }) => <VText title='店铺状态'>
          <div>
            <VStatus status={row.status === '启用'} />
          </div>
        </VText>
      }
    },
    // {
    //   title: '授权状态', field: 'status_info', minWidth: 170, slots: {
    //     default: ({ row }) => <div>
    //       <VText title='授权状态'>
    //         <div><VStatus status={row.auth_status === '正常'} auth /></div>
    //       </VText>
    //       <VText title='有效期' value={row.api_time} />
    //     </div>
    //   }
    // },
    {
      title: '资产信息', field: 'assets_info', minWidth: 220, slots: {
        default: ({ row }) => <div>
          <VText title='紫鸟账号' value={row.assets_info.ziniao_account} />
          <VText title='IP' value={row.assets_info.ziniao_ip} />
          <VText title='存续周期' value={row.assets_info.period} />
          <VText title='续费时间' value={row.assets_info.renewal_time} />
        </div>
      }
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => {
        const { platform_name, shop_name } = JSON.parse(sessionStorage.getItem('_setForm') || '{}')
        if (platform_name === '其他平台') {
          form = { shop_name }
          tableRef?.value.setForm(form)
          sessionStorage.setItem('_setForm', '{}')
        }
        return api.query({ ...form, ...page, platform_id: props.platform_id })
      }
    }
  },
  ...props.tableOpts
})
if(!tableOptions.columns.some(d => d.field === 'handle')) {
  tableOptions.columns.push({
    title: '操作', width: 120, field: 'handle', fixed: 'right', slots: {
      default: ({ row, rowIndex }) => {
        return <div class='nm flex flex-wrap gap-1'>
          <VButton auth={`${authPath}/edit`} link type="primary" onClick={() => handleRow('edit', row)} class='m-0'>编辑</VButton>
          <VButton auth={`${authPath}/delete`} link type="danger" onClick={() => handleRow('delete', row, rowIndex)} class='m-0'>删除</VButton>
          {/* <VButton auth={`${authPath}/delete`} link type="primary" onClick={() => handleRow('updateAuth', row, rowIndex)} class='m-0'>更新授权</VButton> */}
          <VButton auth={`${authPath}/status`} link type="primary" onClick={() => handleRow('status', row)} class='m-0'>{row.status === '启用' ? '禁用' : '启用'}</VButton>
          <VButton auth={`${authPath}/log`} link type="primary" onClick={() => handleRow('log', row)} class='m-0'>查看日志</VButton>
        </div>
      }
    }
  })
}
onActivated(() => {
  const { platform_name, shop_name } = JSON.parse(sessionStorage.getItem('_setForm') || '{}')
  if (platform_name === '其他平台') {
    tableRef?.value.setForm({ shop_name })
    query()
    sessionStorage.setItem('_setForm', '{}')
  }
})

defineExpose({query})
</script>
  